<!DOCTYPE html>
<style>
  iframe {
    height: 300px;
    width: 300px;
  }
</style>

<body>
  <iframe></iframe>
</body>

<script src="../../../resources/testharness.js"></script>
<script src="../../../resources/testharnessreport.js"></script>
<script type="text/javascript">
  'use strict';
  var iframe = document.querySelector('iframe');
  var loadCount = 0;

  // The test does the following navigation steps for iframe
  // 1. load page-with-fragment.html#fragment
  // 2. load blank2
  // 3. go back to page-with-fragment.html 
  async_test(function(t) {
    iframe.src = './resources/page-with-fragment.html#fragment';

    iframe.onload = t.step_func(function() {
      loadCount += 1;
      switch (loadCount) {
        case 1:
          t.step(function() {
            assert_regexp_match(iframe.contentWindow.location.href, /page-with-fragment/, 'should be on page-with-fragment page');
            // wait one animation frame to ensure layout is run and fragment scrolling is complete
            iframe.contentWindow.requestAnimationFrame(function() {
              assert_equals(iframe.contentWindow.scrollY, 800, 'should scroll to fragment');

              iframe.contentWindow.history.scrollRestoration = 'manual';
              assert_equals(iframe.contentWindow.history.scrollRestoration, 'manual');

              // navigate to new page
              setTimeout(function() {
                iframe.src = './resources/blank1.html';
              }, 0);
            });
          });
          break;
        case 2:
          t.step(function() {
            assert_regexp_match(iframe.contentWindow.location.href, /blank1/, 'should be on second blank page');
            assert_equals(iframe.contentWindow.history.scrollRestoration, 'auto', 'new page loads should set scrollRestoration to "auto"');

            setTimeout(function() {
              iframe.contentWindow.history.back();
            }, 0);
          });
          break;
        case 3:
          t.step(function() {
            // coming back from history, scrollRestoration should be set to manual and respected
            assert_regexp_match(iframe.contentWindow.location.href, /page-with-fragment/, 'should be back on page-with-fragment page');
            iframe.contentWindow.requestAnimationFrame(function() {
              assert_equals(iframe.contentWindow.history.scrollRestoration, 'manual', 'navigating back should retain scrollRestoration value');
              assert_equals(iframe.contentWindow.scrollX, 0, 'should not scroll to fragment');
              assert_equals(iframe.contentWindow.scrollY, 0, 'should not scroll to fragment');
              t.done();
            });
          });
          break;
        default:
          assert_unreached('iframe should load 3 times');
      }
    });
  }, 'Manual scroll restoration should take precedent over scrolling to fragment');
</script>